package com.gpj.sqlbuilder.io;

import com.gpj.sqlbuilder.constants.Constants;
import com.gpj.sqlbuilder.store.common.TemplateWraper;
import com.gpj.sqlbuilder.store.sql.Table;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * @className SqlWriter
 * @description
 *   TODO
 * @author GPJ
 * @date 2021/3/26 15:16
 * @version 1.0
 **/
@Slf4j
public class SqlWriter {
    public void writ(String workspace, TemplateWraper template, List<Table> datas) {
        File file = new File(workspace, template.getTemplateFileName() + ".sql");
        if(file.exists()) {
            log.warn("\t\tsql文件[{}]已存在,将删除该文件", file.getName());
            file.delete();
        }
        try (
            BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        ){
            String sql = template.getRoot().sql(datas);
            int index = 0;
            while (index < sql.length()){
                int mark = sql.indexOf(Constants.ENTER_MARK, index);

                if(mark > 0){
                    String line = sql.substring(index, mark).replace(Constants.TABLE_MARK, "\t");
                    log.debug("\t\t开始写入[{}--{}]:{}",index, mark, line);
                    writer.write(line);
                    index = mark + Constants.ENTER_MARK.length();
                    writer.newLine();
                }else{
                    String line = sql.substring(index).replace(Constants.TABLE_MARK, "\t");
                    log.debug("\t\t开始写入[{}--{}]:{}",index, sql.length(), line);
                    writer.write(line);
                    break;
                }
            }
        } catch (IOException e) {
            log.error("\t\tsql输出失败:{}", e.toString(), e);
        }
    }
}

